<?php
class CProductDetail {
	var $product = null;

	/**
	 * Array of property
	 *
	 * @var array
	 */
	var $property_array = null;

	/**
	 * List of gold product in this day
	 *
	 * @var array
	 */
	static $gold_time_products = null;

	function __construct($data) {
		if (is_string($data) || is_numeric($data)) {
			$this->product = CTable('product')->select($data);
		} else if (is_array($data)) {
			$this->product = $data;
		}
	}

	/**
	 * Get list of ProductDetail object from array result of query from sql
	 *
	 * @param array $products
	 * @return array
	 */
	static function getProductDetailList(&$products) {
		$ret = array();
		if(count($products) > 0){
			foreach ($products as &$product) {
				$ret[$product['id']] = new CProductDetail($product);
			}
		}
		return $ret;
	}

	/**
	 * Lấy thông tin số lượng sản phẩm còn được bán trong gio vàng
	 *
	 * @param
	 */
	static function getGoldTimeProduct() {
		if (self::$gold_time_products === null) {
			$timenow = time();
			$gold_time_products = CTable('product_time_gold')->select_all(
				EAnd(
					ELTE('start_date', $timenow),
					EGTE('end_date', $timenow-24*3600)
				)
			);
			self::$gold_time_products = array();
			foreach ($gold_time_products as $key=>$value) {
				self::$gold_time_products[$value['product_id']] = $value;
			}
		}
	}

	/**
	 * Kiểm tra có phải là sản phẩm gio vàng
	 *
	 * @return array
	 */
	var $time_gold_remain = null;
	var $time_gold_total = null;
	function getTimeGoldInfo() {
		if (isset($this->product['types']) && false!==strstr($this->product['types'], '.gold.')) {
			self::getGoldTimeProduct();
			if ($info = @self::$gold_time_products[$this->product['id']]) {
				// Number of minute from start of day
				$time_in_day = time()-strtotime(date('Y-m-d'));
				if ($info['start_hour']<=$time_in_day && $time_in_day<=$info['end_hour']) {
					// Get start time of gold time
					$date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) + $info['start_hour']);
					$condition = array('time_gold_id'=>$info['id'], 'start_time'=>$date);
					if ($this->time_gold_remain === null) {
						if ($product_count = CTable('product_time_gold_count')->select($condition)) {
							$this->time_gold_remain = $product_count['count'];
						} else $this->time_gold_remain = 0;
						$this->time_gold_total = $info['quantity_time_gold'];
						$this->time_gold_remain = $this->time_gold_total - $this->time_gold_remain;
					}
					if ($this->time_gold_remain > 0) {
						return $info;
					} else return null;
				} else {
					return null;
				}
			}
		} else {
			return null;
		}
	}

	/**
	 * Return true if this product is in promotion programe
	 *
	 */
	function isPromoting(&$params) {
		if ($this->getTimeGoldInfo()) {
			$params = new stdClass();
			$params->type = 'giờ vàng';
			$params->title = 'Đang trong chương trình giờ vàng';
			return true;
		}
		$params = null;
		return false;
	}

	/**
	 * Sell product
	 *
	 */
	function checkOut($quantity = 1, $cart_extra_info = array(), $trans_id = 0) {
		// Check for time gold
		// error_log('time_info: '.var_export($this->getTimeGoldInfo(), 1), 3, 'c:/test.txt');
		if (isset($cart_extra_info) && isset($cart_extra_info['time_gold']) && $cart_extra_info['time_gold']==1) {
			if (($info = $this->getTimeGoldInfo())) {
				$date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) + $info['start_hour']);
				$condition = array(
					'time_gold_id' => $info['id'],
					'start_time' => $date
				);

				// error_log('product count: ' . var_export(CTable('product_time_gold_count')->select($condition), 1), 3, 'c:/test.txt');
				if ($product_count = CTable('product_time_gold_count')->select($condition)) {
					CTable('product_time_gold_count')->update(
						array('count'=>$product_count['count']+$quantity),
						$condition
					);
				} else {
					CTable('product_time_gold_count')->insert(
						array('time_gold_id'=>$info['id'], 'start_time'=>$date, 'count'=>$quantity)
					);
				}

				CTable('product_time_gold_transaction')->insert(array(
					'pgt_time_gold_id'		=> $info['id'],
					'pgt_product'					=> $this->getProductId(),
					'pgt_amount'					=> 1,
					'pgt_transaction'			=> $trans_id,
					'pgt_time'						=> date('Y-m-d H:i:s')
				));
			}
		}


		// Clear cache
		// TODO:
	}

	/**
	 * Kiem tra tinh hop le cua 1 product
	 * Gia price > 0, min_price > 0, so luong > 0....
	 * @return bool
	 */
	function isValid() {
		if ($this->product == null) return false;
		if ($this->product['price']<=0 || $this->product['min_price']<=0 || $this->product['market_price']<=0 ||
				$this->product['floor_price']<=0 || $this->product['quantity']<=0) return false;
		return true;
	}

	var $is_sale_off = null;

	/**
	 * Kiem tra xem product co phai dang saleoff ko
	 * @return bool
	 */
	function isSaleOff() {
		if ($this->is_sale_off !== null) return $this->is_sale_off;
		if (isset($this->product['discount_percent']) && $this->product['discount_percent'] &&
			isset($this->product['discount_start_date']) && $this->product['discount_start_date']<time() &&
			$this->product['discount_end_date']+24*3600-1>time() &&
			$this->product['discount_maximum_items']>$this->product['discount_items']) {
			return $this->is_sale_off = true;
		} else {
			return $this->is_sale_off = false;
		}
	}

	function getDiscountPercent() {
		return $this->product['discount_percent'];
	}

	var $real_price = null;
	/**
	 * Lấy giá thực tế của sản phẩm sau khi tính discount
	 * @return Real Price
	 */
	function getRealPrice($vnd = false) {
		if ($this->real_price === null) {
			if ($this->isSaleOff()) {
				$this->real_price = ceil($this->product['price']*(1-$this->product['discount_percent']/100));
			} else {
				$this->real_price = $this->product['price'];
			}
		}

		if ($vnd == false)
			return $this->real_price;
		else
			return CNumber($this->real_price*1000)->price();
	}


	/**
	 * Lấy VAT sản phẩm
	 * @return VAT Price
	 */
	function getVATPrice($vnd = false) {
		$price = $this->getPromotionPrice();
		$vatPrice = ceil(($price*$this->product['tax'])/100);

		if ($vnd == false)
			return $vatPrice;
		else
			return CNumber($vatPrice*1000)->price();
	}

	/**
	 * Lấy giá thực tế của sản phẩm sau khi tính VAT
	 * @return VAT Price
	 */
	function getAfterVATPrice($vnd = false, $incrementTax = false) {
		$price = $this->getPromotionPrice();
		if($incrementTax){
			$price += $this->getVATPrice();
		}

		if ($vnd == false)
			return $price;
		else
			return CNumber($price*1000)->price();
	}

	/**
	 * Lấy giá hiển thị sản phẩm
	 * @return
	 */
	function getDisplayPrice($vnd = false, $tax = false, $type = '') {
		if($type == 'gold') return $this->getPromotionPrice();
		if($tax) return $this->getAfterVATPrice($vnd, $tax);
		else return $this->getRealPrice($vnd);
	}

	function getDisplaySavePrice($vnd = false, $tax = false, $type = '') {
		if($tax) $price = $this->getAfterVATPrice(false, $tax);
		else $price = $this->getRealPrice();
		$save_price = $this->getMarketPrice() - $price;
		if($type == 'gold'){
			return $this->getPromotionSavePrice(1);
		}
		if ($vnd == false) return $save_price;
		else return CNumber($save_price*1000)->price();
	}


	/**
	 * Giá sản phẩm trong giờ vàng
	 *
	 * @param bool $vnd
	 * @return int
	 */
	function getPromotionPrice($vnd = false) {
		if ($info = $this->getTimeGoldInfo()) {
			$price = $info['price'];
		} else {
			$price = $this->getRealPrice();
		}
		if ($vnd == false)
			return $price;
		else
			return CNumber($price*1000)->price();
	}

	function getPromotionSavePrice($vnd = false) {
		$save_price = $this->getMarketPrice() - $this->getPromotionPrice();
		if ($vnd == false)
			return $save_price;
		else
			return CNumber($save_price*1000)->price();
	}

	/**
	 * Lấy giá sản phẩm
	 * @param $vnd false (tính đơn vị nghìn đồng), true (tính đơn vị đồng, dạng xâu ký tự)
	 * @return
	 */
	function getPrice($vnd = false) {
		if ($vnd==false)
			return $this->product['price'];
		else
			return CNumber($this->product['price']*1000)->price();
	}

	/**
	 * Lấy giá tiết kiệm được của sản phẩm
	 *
	 * @param unknown_type $vnd
	 * @return unknown
	 */
	function getSavePrice($vnd = false) {
		if ($vnd==false)
			return $this->getMarketPrice() - $this->getRealPrice();
		else
			return CNumber(($this->getMarketPrice() - $this->getRealPrice())*1000)->price();
	}

	function getSavePercent() {
		$price = $this->getMarketPrice();
		if ($price != 0) return 0;
//		return round(100*$this->getSavePrice()/$price);
	}

	/**
	 * Lấy Min Price
	 * @return min_price
	 */
	function getMinPrice($vnd = false) {
		if ($vnd == false)
			return $this->product['min_price'];
		else
			return CNumber($this->product['min_price']*1000)->price();
	}

	/**
	 * Lấy Min Price đã có thuế
	 * @return min_price
	 */
	function getMinPriceVAT($vnd = false, $incrementVAT = false){
		$minPrice = $this->product['min_price'];
		if($incrementVAT){
			$minPrice += $this->getVATPrice();
		}
		if ($vnd == false)
			return $minPrice;
		else
			return CNumber($minPrice*1000)->price();
	}

	function getMinPriceProduct($vnd = false, $incrementVAT = false){
		if($incrementVAT) $minPrice = $this->getMinPriceVAT();
		else $minPrice = $this->getMinPrice();
		if ($vnd == false)
			return $minPrice;
		else
			return CNumber($minPrice*1000)->price();
	}

	/**
	 * Return market price
	 *
	 * @param bool $vnd
	 * @return
	 */
	function getMarketPrice($vnd = false) {
		if ($vnd == false)
			return $this->product['market_price'];
		else
			return CNumber($this->product['market_price']*1000)->price();
	}

	function getProductId() {
		return $this->product['id'];
	}

	/**
	 * Lấy tên sản phẩm
	 * @return product name
	 */
	function getName() {
		return $this->product['name'];
	}

	/**
	 * Category of product
	 * @return string
	 */
	function getCategoryId() {
		return $this->product['category_id'];
	}

	//Quyen
	function getUnsignedName(){
		if (isset($this->product['unsigned_name']))
		    return $this->product['unsigned_name'];
		else
		{
		    return '';
		}
	}

	function getThumbnail() {
		return $this->product['thumbnail'];
	}
	function getImage() {
		return $this->product['image'];
	}

	function getMediumThumbnail() {
		return $this->product['medium'];
	}

	function getCommentCount() {
		return $this->product['comment_count'];
	}

	function getViewCount() {
		return $this->product['view_count'];
	}

	function getMedia() {
		return $this->product['media'];
	}

	function getFlash() {
		return $this->product['flash'];
	}

	function getQuantity() {
		return intval($this->product['quantity']);
	}
	function getWarranty() {
		return intval($this->product['warranty']);
	}

	/**
	 * Check wether product is kind of type (new, commingsoon, saleoff, gold...)
	 *
	 * @param unknown_type $type
	 * @return unknown
	 */
	function isType($type) {
		return isset($this->product['types']) && false !== strpos($this->product['types'], $type.'.');
	}

	/**
	 * Properties Product dạng html.
	 * @return cache_all_properties
	 */
	function getHtmlProperties() {
		if(isset($this->product['cache_all_properties'])){
			return $this->product['cache_all_properties'];
		}
	}

	function getShortHtmlProperties() {
		return $this->product['cache_properties'];
	}

	/**
	 * Properties Product dạng array
	 * @return properties
	 */
	function &getProperties() {
		if (!isset($this->property_array)) {
			eval('$this->property_array='.$this->product['properties'].';');
		}
		return $this->property_array;
	}

	/**
	 * Enter description here...
	 *
	 */
	function getPromotionValue() {
		$this->getProperties();
		return @$this->property_array['ShowTooltip']['SaleOff'];
	}

	/**
	 * Enter description here...
	 *
	 */
	function getDetailInformation() {
		if ($reference_id = $this->product['reference_id']) return;
		$secondary_fields = 'id,name,price,min_price,market_price,quantity,view_count,
			image,large,medium,media,flash,discount_percent,discount_maximum_items,discount_items,reference_id,types';

		if (!$this->product['thumbnail'] &&
		$reference = CTable('product')->fields($secondary_fields)->select(array('code'=>$reference_id))) {
			$this->product['thumbnail'] = $reference['thumbnail'];
			$this->product['small'] = $reference['small'];
			$this->product['large'] = $reference['large'];
			$this->product['medium'] = $reference['medium'];
			$this->product['image'] = $reference['image'];
		}

		$products = CTable('product')->fields($secondary_fields)->select_all(
				EAnd(
					EEqual('reference_id', EString($reference_id)),
					EGT('min_price', 0), EGT('price', 0), EGT('market_price', 0),
					EGT('status', 0), EGT('quantity', 0)));

		if (isset($reference)) $products[] = $reference;

		$this->product['name'] = str_replace(array('"', '\''),array('&quot;', '&rsquo;'),$this->product['name']);

		// Xử lý phân loại ảnh theo màu
		$this->colors = array();

		// color
		$define_colors = CTable('colors/color/name|colors/color/label')
			->change_store(new CDataXmlStore(DATA_DIR.portal()->id.'/colors.xml','/root/'))->select_all();
		$define_colors = $this->normalize($define_colors);
		$this->get_colors($this->product);

		foreach($products as &$product) {
			if ($product['id'] == $product_id) continue;
			if (!$this->product['large'] and $product['reference_id'] == '' and $product['large']) {
				$this->product['large'] = $product['large'];
			}
			$this->get_colors($product);
		}

		foreach($this->colors as &$color) {
			$color['title'] = $define_colors[$color['id']];
			foreach ($color['images'] as &$pcolor) {
				$pcolor['title'] = $define_colors[$pcolor['color']];
			}
		}
	}

	/**
	 * Check for subtitute product
	 *
	 * @return unknown
	 */
	function checkSubtitute() {
		if ($this->isValid()) return true;
		if ($subtitute_id = $this->product['substitute_id']) {
			$product = CTable('product')->select(
				EAnd(
					EEqual('id', $subtitute_id),
					EGT('min_price', 0),
					EGT('price', 0),
					EGT('market_price', 0),
					EGT('status', 0),
					EGT('quantity', 0)
				)
			);
			if ($product) {
				if (!$product['thumbnail']) {
					$product['thumbnail'] = $this->product['thumbnail'];
				}
				$this->product = $product;
				return true;
			}
		}
		$this->product = null;
		return false;
	}

	function getMaxCommission($vnd = false) {
		if ($vnd == false)
			return $this->getDisplayPrice() - $this->getMinPriceProduct();
		else
			return CNumber(($this->getDisplayPrice() - $this->getMinPriceProduct())*1000)->price();
	}

	/**
	 *
	 * @param string $property_name name of property (in $product array)
	 * @return mixed value of property
	 */
	function get($property_name) {
		return $this->product[$property_name];
	}
}